#!usr/bin/python
# -*- coding: utf-8 -*-
from app.get_redis import connect_redis
from config import Config
import requests


def get_token():
    conn = connect_redis()
    # token = conn.get('access_token')  避免和服务器上别的access_token重复，另起一个key的名字
    token_tmpl = conn.get('stu_token')
    if not token_tmpl:
        result = requests.get(Config.TOKEN_URL).json()
        token = result.get('access_token')  # 获取token
        expires_in_seconds = int(result.get('expires_in') * 0.1)    # 获取token的过期时间
        print expires_in_seconds
        conn.set(
            name='stu_token',
            value=token,
            ex=expires_in_seconds   # 第三个参数表示Redis过期时间
        )
        # 存到Redis
    else:
        token = token_tmpl.decode("utf8")  # 解码

    return token
    # access_token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
    # payload = {'corpid': 'wxccf4abb85e4bddfc', 'corpsecret': 'LvEl5O3g1tnw_0Tg_PbyJjYvxIOWN_QRusShvYqap1E'}
    # json_info = requests.get(access_token_url, params=payload, verify=False).json()
    # if not json_info.get('errcode') == 0:
    #     errcode = json_info['errcode']
    #     print errcode  # tornado.ioloop.IOLoop.instance ().call_later (10, self.get_access_token)
    # else:
    #     access_token = json_info.get('access_token')
    #
    #     return access_token

